{% load i18n %}
<div class="row">
<div class="col-sm-offset-2 col-sm-9"><p>{% trans "Run a sequence of tasks, and schedule it to run automatically." %}</p></div>
</div>
<div class="row">
<div class="col-sm-2"></div>
<div class="col-sm-6"><p><strong>{% trans "name"|capfirst %}</strong></p></div>
<div class="col-sm-3"><p><strong>{% trans "next scheduled run"|capfirst %}</strong></p></div>
</div>
{% for schedule in schedules %}
<div class="row{% if not schedule.name %} hidden" id="scheduledtask_headertemplate{% endif %}" data-schedule-name="{{ schedule.name }}" style="padding-top:5px; padding-bottom:5px">
  <div class="col-sm-2 text-center">
    <form role="form" method="post" action="{{request.prefix}}/execute/launch/scheduletasks/">{% csrf_token %}
    <button type="submit" class="btn btn-primary btn-block">{% trans "launch"|capfirst %}</button>
    <input type="hidden" name="schedule" value="{{schedule.name}}">
    </form>
  </div>
  <div class="col-sm-6" data-field="name" style="padding-top:6px; padding-bottom:6px">{{ schedule.name }}</div>
  <div class="col-sm-3" data-field="next-run" style="padding-top:6px; padding-bottom:6px">
  {% if schedule.next_run %}{{ schedule.next_run|date:"Y-m-d H:i:s" }}{% endif %}
  </div>
  {% if perms.execute.change_scheduledtask %}
  <div class="col-sm-1 text-center" style="padding-top:6px; padding-bottom:6px">
  <button class="btn btn-xs btn-primary" onclick="editScheduledTask(this, event)">
  <span class="fa fa-edit" data-toggle="tooltip" 
    data-placement="top" data-original-title="{% trans "Edit" %}"></span>
  </button>
  </div>
  {% endif %}
</div>
{% if perms.execute.change_scheduledtask %}
<div class="row{% if not schedule.name %} hidden" id="scheduledtask_template{% endif%}" data-schedule-name="{{ schedule.name }}"
  style="display:none; padding:10px; border-style:solid; border-radius:10px; border-width:1px; margin:10px 0 10px 0">
  <div class="col-sm-2 text-center">
    <div>
      <button class="btn btn-primary btn-block" style="margin-bottom:20px; margin-top: 15px" onclick="saveScheduledTask(this, event)">
      {% trans "Save" %}</button>
    </div>
    <div>  
      <button class="btn btn-primary btn-block" onclick="deleteScheduledTask(this, event)">
      {% trans "Delete" %}
      </button>
    </div>
  </div>
  <div class="col-sm-10">
    <div class="row" style="padding-bottom:10px">
       <div style="float:right">
         <button type="button" class="close" onclick="closeScheduledTask(this, event)">
         <span aria-hidden="true" class="fa fa-times"></span>
         </button>
      </div>
    </div>    
    <div class="form-horizontal">
       <div class="form-group">
         <label for="schedule-{{forloop.counter}}-name" class="col-sm-3 control-label">{% trans "name"|capfirst %}</label>
         <div class="col-sm-9">
           <input type="text" class="form-control" id="schedule-{{forloop.counter}}-name"
             data-field="name" value="{{schedule.name}}" placeholder="{% trans "unique name"|capfirst %}">
         </div>
       </div>
       <div class="form-group">
         <label class="col-sm-3 control-label">{% trans "tasks"|capfirst %}</label>
         <div class="col-sm-9">
         {% for t in schedule.data.tasks %}
         <div class="form-group data-task">
         <div class="col-xs-4">
            <div class="btn-group btn-block">
            <button data-field="task-name" data-name="{{ t.name }}" type="button"
              class="btn btn-block btn-primary dropdown-toggle" data-toggle="dropdown">
              {{ t.name }}&nbsp;<span class="caret"></span>
            </button>
            <ul class="dropdown-menu" role="menu">
              {% for c in commands %}
              <li><a href="#" onclick="setTaskType(this, event)">{{c}}</a></li>
              {% endfor %}
            </ul>
            </div>
         </div>
         <div class="col-xs-6">
         <input data-field="task-arguments" class="form-control" type="text" placeholder="{% trans "Arguments" %}" value="{{ t.arguments }}">
         </div>
         <div class="col-xs-1">
         <input data-field="task-abort-on-failure" type="checkbox" value="1" {% if t.abort_on_failure %}checked{% endif %}
           class="form-check-input" data-toggle="tooltip" data-placement="top" data-original-title="{% trans "abort on failure"|capfirst %}">
         </div>
         <div class="col-xs-1">
         <button class="btn btn-xs btn-primary" onclick="deleteTask(this, event)">         
         <span class="fa fa-trash-o" data-toggle="tooltip" data-placement="top"
           data-original-title="{% trans "Delete" %}"></span>
         </button>
         </div>
         </div>
         {% endfor %}
         <!-- extra empty row for new tasks -->
         <div id="addScheduledTask" class="form-group">
         <div class="col-sm-1 pull-right">
         <button class="btn btn-xs btn-primary" onclick="addTask(this, event)">
         <span class="fa fa-plus" data-toggle="tooltip" data-placement="top" data-original-title="{% trans "Add" %}"></span>
         </button>
         </div>
         </div>
         </div>
       </div>       
 		   <div class="form-group">
         <label for="schedule-{{forloop.counter}}-start" class="col-sm-3 control-label">{% trans "start time"|capfirst %}</label>
         <div class="col-sm-9">
           <input type="text" class="form-control" id="schedule-{{forloop.counter}}-at"
             data-field="starttime" placeholder="HH:MM:SS"
             {% if schedule.data.starttime < 86400 and schedule.data.starttime > 0 %}value="{{schedule.data.starttime|timeformat}}"{% endif %}>
         </div>
       </div>
       <div class="form-group">
         <label class="col-sm-3 control-label">{% trans "weekly schedule"|capfirst %}</label>
		     <div class="col-sm-9">
					 <label class="checkbox-inline">
					   <input data-field="monday" type="checkbox" {% if schedule.data.monday %}checked{% endif %}>{% trans "Mon" %}
					 </label>
           <label class="checkbox-inline">
             <input data-field="tuesday" type="checkbox" {% if schedule.data.tuesday %}checked{% endif %}>{% trans "Tue" %}
           </label>
           <label class="checkbox-inline">
             <input data-field="wednesday" type="checkbox" {% if schedule.data.wednesday %}checked{% endif %}>{% trans "Wed" %}
           </label>
           <label class="checkbox-inline">
             <input data-field="thursday" type="checkbox" {% if schedule.data.thursday %}checked{% endif %}>{% trans "Thu" %}
           </label>
           <label class="checkbox-inline">
             <input data-field="friday" type="checkbox" {% if schedule.data.friday %}checked{% endif %}>{% trans "Fri" %}
           </label>
           <label class="checkbox-inline">
             <input data-field="saturday" type="checkbox" {% if schedule.data.saturday %}checked{% endif %}>{% trans "Sat" %}
           </label>
           <label class="checkbox-inline">
             <input data-field="sunday" type="checkbox" {% if schedule.data.sunday %}checked{% endif %}>{% trans "Sun" %}
           </label>
		     </div>
		   </div>       
       <div class="form-group">
         <label for="schedule-{{forloop.counter}}-email-success" class="col-sm-3 control-label">{% trans "email on success"|capfirst %}</label>
         <div class="col-sm-9">
           <input type="email" class="form-control" id="schedule-{{forloop.counter}}-email-success" 
              placeholder="{% trans "list of emails, separated by commas"|capfirst %}" data-field="email_success" 
              {% if schedule.email_success %}value="{{schedule.email_success}}"{% endif %}>
         </div>
       </div>
       <div class="form-group">
         <label for="schedule-{{forloop.counter}}-email-failure" class="col-sm-3 control-label">{% trans "email on failure"|capfirst %}</label>
         <div class="col-sm-9">
           <input type="email" class="form-control" id="schedule-{{forloop.counter}}-email-failure"
             placeholder="{% trans "list of emails, separated by commas"|capfirst %}" data-field="email_failure"
              {% if schedule.email_failure %}value="{{schedule.email_failure}}"{% endif %}>
         </div>
       </div>
    </div>
   </div>
   {% endif %}
</div>
{% endfor %}
{% if perms.execute.add_scheduledtask %}
<div class="row">
<div class="col-sm-offset-11 col-sm-1 text-center">
<button class="btn btn-xs btn-primary" onclick="addScheduledTask(this, event)">
<span class="fa fa-plus" data-toggle="tooltip" data-placement="top" data-original-title="{% trans "Add" %}"></span>
</button>
</div>
</div>
<div id="scheduledtask_tasktemplate" class="hidden form-group data-task">
         <div class="col-xs-4">
            <div class="btn-group btn-block">
            <button data-field="task-name" type="button"
              class="btn btn-block btn-primary dropdown-toggle" data-toggle="dropdown">
              <span class="caret"></span>
            </button>
            <ul class="dropdown-menu" role="menu">
              {% for c in commands %}
              <li><a href="#" onclick="setTaskType(this, event)">{{c}}</a></li>
              {% endfor %}
            </ul>
            </div>
         </div>
         <div class="col-xs-6">
         <input data-field="task-arguments" class="form-control" type="text" placeholder="{% trans "Arguments" %}">
         </div>
         <div class="col-xs-1">
         <input data-field="task-abort-on-failure" type="checkbox" value="1"
           data-toggle="tooltip" data-placement="top" data-original-title="{% trans "abort on failure"|capfirst %}">
         </div>
         <div class="col-xs-1">
         <button class="btn btn-xs btn-primary" onclick="deleteTask(this, event)">         
         <span class="fa fa-trash-o" data-toggle="tooltip" data-placement="top"
           data-original-title="{% trans "Delete" %}"></span>
         </button>
         </div>
</div>
{% endif %}

<script>
function setTaskType(el, event) {
	var tgt = $(el);
	var parent = tgt.parents("ul").prev();
	parent.html(tgt.html() + '&nbsp;<span class="caret"></span>');
	parent.attr("data-name", tgt.html()); 
	event.preventDefault();
}

function deleteTask(el, event) {
	$(el).closest(".data-task").remove();
  event.preventDefault();
}

function addTask(el, event) {
	var newrow = $("#scheduledtask_tasktemplate").clone();
  newrow.removeAttr("id");
	newrow.insertBefore($(el).closest(".form-group"));
  newrow.toggleClass("hidden");
  event.preventDefault();
}

function addScheduledTask(el, event) {
  var newrow = $("#scheduledtask_template").clone();
  newrow.removeAttr("id");
  newrow.insertBefore($(el).closest(".row"));
  newrow.removeClass("hidden").toggle();
  event.preventDefault();
}

function editScheduledTask(el, event) {
  var tgt = $(el);
  tgt.closest('.row').toggle();
  tgt.closest('.row').next().toggle();
  event.preventDefault();
}

function closeScheduledTask(el, event) {
  var row = $(el).closest('[data-schedule-name]');
  row.toggle();
  row.prev().toggle();
  event.preventDefault();
}

function saveScheduledTask(el, event) {
  var tgt = $(el);
  var form = tgt.closest('[data-schedule-name]');
  var starttime = new moment(form.find("[data-field='starttime']").val(), "HH:mm:ss");
  var tasks = [];
  form.find(".data-task").each(function(i, el){
  	var t = $(this);
  	var n = t.find("[data-field='task-name']").attr("data-name");
  	if (n)
  	  tasks.push({
  		  "name": n,
  		  "arguments": t.find("[data-field='task-arguments']").val(),
  		  "abort_on_failure": t.find("[data-field='task-abort-on-failure']").is(":checked")
  	  });
  });
  var schedname = form.find("[data-field='name']").val();
  var oldschedname = form.attr("data-schedule-name");
  $.ajax({
    url: url_prefix + "/execute/scheduletasks/",
    type: 'POST',
    data: JSON.stringify({
      "name": schedname,
      "oldname": oldschedname,
      "email_failure": form.find("[data-field='email_failure']").val(),
      "email_success": form.find("[data-field='email_success']").val(),
      "data": {
        "starttime": starttime.hours() * 3600 + starttime.minutes() * 60 + starttime.seconds(),
        "monday": form.find("[data-field='monday']").is(":checked"),      
        "tuesday": form.find("[data-field='tuesday']").is(":checked"),      
        "wednesday": form.find("[data-field='wednesday']").is(":checked"),      
        "thursday": form.find("[data-field='thursday']").is(":checked"),      
        "friday": form.find("[data-field='friday']").is(":checked"),      
        "saturday": form.find("[data-field='saturday']").is(":checked"),      
        "sunday": form.find("[data-field='sunday']").is(":checked"),
        "tasks": tasks
        }
    }),
    success: function(data) {
    	if (oldschedname === "") {
    	  // Added new schedule
    	  var newrow = $("#scheduledtask_headertemplate").clone();
    	  newrow.removeAttr("id");
    	  newrow.insertBefore(form);
    	  newrow.removeClass("hidden").toggle();    	  
    	}    	  
    	form.prev().toggle();
      form.prev().find("[data-field='next-run']").text(data);
      form.prev().find("[data-field='name']").text(schedname);
      form.prev().find("input[name='schedule']").val(schedname);
      form.prev().attr("data-schedule-name", schedname);
      form.attr("data-schedule-name", schedname);
      form.toggle();
    },
    error: function(jqXHR, status, errorThrown) {
      $('#popup').html('<div class="modal-dialog">'+
          '<div class="modal-content">'+
            '<div class="modal-header bg-danger">'+
              '<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true" class="fa fa-times"></span></button>'+
              '<h4 class="modal-title">'+ gettext("Error")+'</h4>'+
            '</div>'+
            '<div class="modal-body">'+
              '<p>'+jqXHR.responseText+'</p>'+
            '</div>'+
            '<div class="modal-footer">'+
              '<input type="submit" id="cancelbutton" role="button" class="btn btn-primary pull-right" data-dismiss="modal" value="'+gettext('Close')+'">'+
            '</div>'+
          '</div>'+
      '</div>' )
      .modal('show');
    }
    });
  event.preventDefault();
}

function deleteScheduledTask(el, event) {
  event.preventDefault();
	var sched = $(el).closest("[data-schedule-name]");
  $.ajax({
    url: url_prefix + "/execute/scheduletasks/",
    type: 'DELETE',
    data: JSON.stringify({name: sched.attr("data-schedule-name")}),
    success: function() {
    	sched.prev().remove();
    	sched.remove();
    },
    error: function(jqXHR, status, errorThrown) {
    	$('#popup').html('<div class="modal-dialog">'+
          '<div class="modal-content">'+
            '<div class="modal-header bg-danger">'+
              '<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true" class="fa fa-times"></span></button>'+
              '<h4 class="modal-title">'+ gettext("Error")+'</h4>'+
            '</div>'+
            '<div class="modal-body">'+
              '<p>'+jqXHR.responseText+'</p>'+
            '</div>'+
            '<div class="modal-footer">'+
              '<input type="submit" id="cancelbutton" role="button" class="btn btn-primary pull-right" data-dismiss="modal" value="'+gettext('Close')+'">'+
            '</div>'+
          '</div>'+
      '</div>' )
      .modal('show');
    }
    });
}

</script>